# -*- coding: utf-8 -*-
import json

from common.channel.model import *
from common.utils import track_logging
from common.utils.db import list_object
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_all_available_channels():
    return Channel.query.filter(Channel.status == 1).all()


@sql_wrapper
def get_mch_available_channels(mch_id):
    return Channel.query.filter(Channel.mch_id == mch_id).filter(Channel.status == 1).all()


@sql_wrapper
def get_channels_in_ids(ids):
    if not ids:
        return []
    return Channel.query.filter(Channel.id.in_(ids)).filter(Channel.status == 1).all()


@sql_wrapper
def create_channel(name, service_name, chn_type, open_type, info):
    account = Channel()
    account.name = name
    account.service_name = service_name
    account.chn_type = chn_type
    account.open_type = open_type
    account.info = json.dumps(info, ensure_ascii=False)
    account.status = 0
    account.save()
    return account


@sql_wrapper
def get_channel_status(channel_id):
    return Channel.query.filter(Channel.id == channel_id).first().status


@sql_wrapper
def get_channel(channel_id):
    return Channel.query.filter(Channel.id == channel_id).first()


@sql_wrapper
def set_channel_status(channel_id, status):
    item = Channel.query.filter(Channel.id == channel_id).first()
    if item is None:
        return
    item.status = status
    item.save()


@sql_wrapper
def channel_copy(id):
    item = Channel.query.filter(Channel.id == id).first()
    if item is None:
        return
    c = Channel()
    c.name = u'[复制]' + item.name
    c.service_name = item.service_name
    c.chn_type = item.chn_type
    c.mch_id = item.mch_id
    c.weight = item.weight
    c.levels = item.levels
    c.open_type = item.open_type
    c.info = item.info
    c.status = item.status
    c.quotas = item.quotas
    c.rate = item.rate
    c.settlement_method = item.settlement_method
    c.ip_white_list = item.ip_white_list
    c.save()


@sql_wrapper
def scan_repeat_no(pay_type, order_no, third_no, trans_no, amount):
    query = ScanRepeatNo.query.filter(ScanRepeatNo.trans_no == trans_no).first()
    if query:
        return
    s = ScanRepeatNo()
    s.pay_type = pay_type
    s.order_no = order_no
    s.third_no = third_no
    s.trans_no = trans_no
    s.amount = amount
    s.save()


@sql_wrapper
def list_repest_no(query_dct):
    return list_object(query_dct, ScanRepeatNo)


@sql_wrapper
def handle_repeat_order(id, operater, operater_id, msg=''):
    item = ScanRepeatNo.query.filter(ScanRepeatNo.id == int(id)).filter(ScanRepeatNo.status == 0).first()
    if item is None:
        return
    item.status = 1
    item.operater = operater
    item.operater_id = operater_id
    item.msg = msg
    item.save()
